package com.practice.text;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class ConvertText {

	private static final int BUFFER_LENGTH = 0x400;

	private static final String OLD_DIR_PATH = "";

	private static final String NEW_DIR_PATH = "";

	private static final FileFilter CONVERT_FILE_FILTER = file -> file.getName().endsWith(".java");

	public static void main(String[] args) {
		File oldDir = new File(OLD_DIR_PATH);
		File newDir = new File(NEW_DIR_PATH);
		convertDir(oldDir, newDir);
	}

	private static void convertDir(File oldDir, File newDir) {
		if (!newDir.exists()) {
			newDir.mkdir();
		}

		File[] oldFiles = oldDir.listFiles(File::isFile);
		for (File oldFile : oldFiles) {
			String fileName = oldFile.getName();
			File newFile = new File(newDir, fileName);
			convertFile(oldFile, newFile);
		}

		File[] oldsubDirs = oldDir.listFiles(File::isDirectory);
		for (File oldSubDir : oldsubDirs) {
			String dirName = oldSubDir.getName();
			File newSubDir = new File(newDir, dirName);
			convertDir(oldSubDir, newSubDir);
		}
	}

	private static void convertFile(File oldFile, File newFile) {

		if (CONVERT_FILE_FILTER != null && !CONVERT_FILE_FILTER.accept(oldFile)) {
			return;
		}
		
		System.out.println("Convert from " + oldFile.getAbsolutePath() + " to " + newFile.getAbsolutePath());
		
		try (Reader reader = new FileReader(oldFile); Writer writer = new FileWriter(newFile)) {
			char[] buffer = new char[BUFFER_LENGTH];
			int readLength = -1;
			while ((readLength = reader.read(buffer, 0, BUFFER_LENGTH)) > -1) {
				for (int i = 0; i < readLength; i++) {
					if (buffer[i] != '\r')
						writer.write(buffer[i]);
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}
